import { useQuery } from '@tanstack/react-query';
import { Collapse, Form, Select, Image, Pagination, Button, message, InputNumber } from 'antd';
import { useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';

import commonService from '@/api/services/commonService';
import img1 from '@/assets/img/1.png';
import img2 from '@/assets/img/2.png';
import img3 from '@/assets/img/3.png';
import img4 from '@/assets/img/4.png';
import img5 from '@/assets/img/5.png';
import FavIcon from '@/assets/img/collect_off.png';
import FavOnIcon from '@/assets/img/collect_on.png';
import { CartModal } from '@/components/CommonButtons/modal';
import userStore from '@/store/userStore';
import { toGoodsDetail } from '@/utils';

import './index.css';

const { Panel } = Collapse;

const useHashParams = () => {
  const location = useLocation();
  const [hashParams, setHashParams] = useState<{ [key: string]: string }>({});

  useEffect(() => {
    const { hash } = window.location;
    const query = new URLSearchParams(hash.split('?')[1]);
    const params: { [key: string]: string } = {};
    query.forEach((value, key) => {
      params[key] = value;
    });
    setHashParams(params);
  }, [location]);

  return hashParams;
};

export default function GoodsPage() {
  const [form] = Form.useForm();
  const [base, setBase] = useState<any>({});
  const [list, setList] = useState<any>([]);
  const [query, setQuery] = useState<any>({
    pageSize: 12,
    pageNo: 1,
  });
  const [showModal, setShowModal] = useState<boolean>(false);
  const [pkInfo, setPkInfo] = useState<any>({});

  const imgMap: any = {
    1: img1,
    2: img2,
    3: img4,
    4: img3,
    5: img5,
  };

  const hashParams = useHashParams();

  useEffect(() => {
    setQuery({ ...query, ...hashParams });
  }, [hashParams]);

  const handleChange = (e: any, data: any) => {
    setQuery({ ...query, ...data });
    console.log(e, data);
  };

  const doFav = async (item: any) => {
    await commonService.collectApi('collect', { targetId: item.id, type: 1 });
    message.success('收藏成功！');
    refetch();
  };

  const { data = {}, refetch } = useQuery({
    queryKey: ['mall', query],
    queryFn: async () => {
      const params: any = {};
      Object.keys(query).forEach((key) => {
        if (query[key] || query[key] === 0) {
          params[key] = query[key];
        }
      });
      return commonService.getFrontApi('mall', params);
    },
  });

  useEffect(() => {
    commonService.getBaseApi().then((res) => {
      setBase(res);
    });
    commonService.getCustomApi('/common/designer/getPreProductGroup', {}).then((res) => {
      setList(res);
    });
    if (sessionStorage.keyword) {
      query.keyword = sessionStorage.keyword;
      sessionStorage.removeItem('keyword');
    }
  }, []);

  const toDetail = (item: any) => {
    toGoodsDetail(item);
  };

  const toAddCart = (e: any, item: any) => {
    e.stopPropagation();
    const token = userStore.getState().userToken;
    if (token.accessToken) {
      setPkInfo(item);
      setShowModal(true);
    } else {
      tipLogin();
    }
  };

  const tipLogin = () => {
    console.log('按钮点击登录');
    userStore.getState().actions.setShowLogin(true);
    message.warning('请登录');
  };

  return (
    <div className="relative left-[50%] ml-[-712px] mt-[40px] flex w-[1424px] flex-col">
      <div>首页 / 购物</div>
      <div className="font-weight mb-[40px] mt-[20px] text-[32px]">我们的畅销产品</div>
      <div className="flex">
        <div className="mr-[50px] flex w-[354px] flex-col">
          <Collapse defaultActiveKey={1} ghost expandIconPosition="end">
            <Panel header="类别" key="1">
              <div className="flex flex-col gap-[10px]">
                {base.suitFor
                  ? base.suitFor.map((item: any) => {
                      return (
                        <div
                          className={[
                            'flex cursor-pointer gap-[10px]',
                            query.suitFor == item.value ? 'font-bold text-[#FD7901]' : '',
                          ].join(' ')}
                          onClick={() =>
                            handleChange(item.value, { ...query, suitFor: item.value })
                          }
                          key={item.value}
                        >
                          <img className="w-[20px]" src={imgMap[item.value]} alt="img" />
                          {item.name}
                        </div>
                      );
                    })
                  : ''}
              </div>
            </Panel>
          </Collapse>
          <div className="border-1 my-[40px]">
            <Collapse defaultActiveKey={1} ghost expandIconPosition="end">
              <Panel header="产品" key={1}>
                {list.map((item: any) => {
                  return (
                    <Collapse key={item.id} ghost expandIconPosition="end">
                      <Panel header={item.name} key={item.id}>
                        <div className="flex flex-col gap-[10px]">
                          {item.sonList.map((sub: any) => {
                            return (
                              <div
                                onClick={() => setQuery({ ...query, catalogueId: sub.id })}
                                key={sub.id}
                                className={[
                                  'flex cursor-pointer flex-col gap-[10px]',
                                  query.catalogueId == sub.id ? 'font-weight text-[#FD7901]' : '',
                                ].join(' ')}
                              >
                                {sub.name}
                              </div>
                            );
                          })}
                        </div>
                      </Panel>
                    </Collapse>
                  );
                })}
              </Panel>
            </Collapse>
          </div>
        </div>
        <div className="flex-1 flex-col">
          <div className="flex">
            <Form
              initialValues={query}
              form={form}
              labelCol={{ span: 0 }}
              wrapperCol={{ span: 8 }}
              onValuesChange={handleChange}
              layout="inline"
            >
              <Form.Item<any> label="尺寸" name="size" required>
                <Select
                  style={{ width: '100px' }}
                  placeholder="尺码"
                  options={
                    base.sizes
                      ? base.sizes.map((item: string) => ({
                          label: item,
                          value: item,
                        }))
                      : []
                  }
                />
              </Form.Item>
              <Form.Item<any> label="颜色" name="color" required>
                <Select
                  style={{ width: '100px' }}
                  placeholder="颜色"
                  options={
                    base.color
                      ? base.color.map((item: string) => ({
                          label: item,
                          value: item,
                        }))
                      : ''
                  }
                />
              </Form.Item>
              <Form.Item<any> label="材质" name="material" required>
                <Select
                  style={{ width: '100px' }}
                  placeholder="材质"
                  options={
                    base.material
                      ? base.material.map((item: string) => ({
                          label: item,
                          value: item,
                        }))
                      : ''
                  }
                />
              </Form.Item>
              <Form.Item<any> noStyle>
                <Form.Item<any> name="minimumPrice" required>
                  <InputNumber
                    formatter={(value) => `￥${value}`}
                    style={{ width: '100px' }}
                    placeholder="最低价格"
                  />
                </Form.Item>
                <Form.Item<any> name="maximumPrice" required>
                  <InputNumber
                    formatter={(value) => `￥${value}`}
                    style={{ width: '100px' }}
                    placeholder="最高价格"
                  />
                </Form.Item>
              </Form.Item>
            </Form>
          </div>
          {/* <div className="my-[10px] flex justify-end leading-[24px] text-[#686B73]">
            更改视图: 产品|设计
          </div> */}
          {/** 商品列表 */}
          <div className="flex-start mt-[20px] flex flex-wrap gap-[20px]">
            {data.list
              ? data.list.map((item: any) => {
                  const thumbs = JSON.parse(item.thumbs || '[]');
                  const defaultSrc = thumbs[0];
                  const hoverSrc = thumbs[1];
                  return (
                    <div
                      key={item.id}
                      className="relative mb-[32px] flex w-[240px] cursor-pointer flex-col leading-[24px]"
                    >
                      <div className="relative overflow-hidden">
                        <div className="image-container" onClick={() => toDetail(item)}>
                          <div className="default-image">
                            <Image alt={item.goodsName} src={defaultSrc} preview={false} />
                          </div>
                          <div className="hover-image">
                            <Image
                              alt={item.goodsName}
                              src={hoverSrc || defaultSrc}
                              preview={false}
                            />
                          </div>
                          <div className="hover-button w-[240px]">
                            <Button type="primary" onClick={(e) => toAddCart(e, item)}>
                              加入购物车
                            </Button>
                          </div>
                        </div>
                        <div
                          className="absolute right-[10px] top-[10px] !w-[34px]"
                          onClick={(e) => {
                            e.stopPropagation();
                            doFav(item);
                          }}
                        >
                          <Image src={true ? FavIcon : FavOnIcon} preview={false} alt="fav" />
                        </div>
                      </div>
                      <div className="mt-[16px]">{item.goodsName}</div>
                      <div className="mt-[4px] text-[#686B73]">{item.material}</div>
                      <div className="mt-[4px] text-[20px] leading-[30px]">
                        ￥{(item.price / 100).toFixed(2)}起
                      </div>
                    </div>
                  );
                })
              : ''}
          </div>
          <div className="flex justify-around py-[20px]">
            <Pagination
              current={data.pageNo}
              pageSize={data.pageSize}
              total={data.totalCount}
              onChange={(e) => setQuery({ ...query, pageNo: e })}
              showSizeChanger={false}
            />
          </div>
        </div>
      </div>
      <CartModal showModal={showModal} good={pkInfo} onClose={() => setShowModal(false)} />
    </div>
  );
}
